import { userBehavior } from './behavior'
import { getStorage, setStorage } from '@/utils/storage'
import { toast } from '@/utils/extendApi'
import { reqUploadFile, reqUpdateUserInfo } from '@/api/user'

Page({
  behaviors: [userBehavior],

  data: {
    isShowPopup: false
  },

  async updateUserInfo() {
    const res = await reqUpdateUserInfo(this.data.userInfo)
    if (res.code === 200) {
      setStorage('userInfo', this.data.userInfo)
      this.setUserInfo(this.data.userInfo)
      toast({ title: '用户信息更新成功' })
    }
  },

  async chooseAvatar(event) {
    const { avatarUrl } = event.detail
    const res = await reqUploadFile(avatarUrl, 'file')
    this.setData({
      'userInfo.headimgurl': res.data
    })
  },

  getNickName(event) {
    const { nickname } = event.detail.value
    this.setData({
      'userInfo.nickname': nickname,
      isShowPopup: false
    })
  },

  onUpdateNickName() {
    this.setData({
      isShowPopup: true,
      'userInfo.nickname': this.data.userInfo.nickname
    })
  },

  cancelForm() {
    this.setData({
      isShowPopup: false
    })
  }
})
